package com.shengdou.as.slopsapptest.receiver;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

import com.shengdou.as.slopsapptest.R;
import com.shengdou.as.slopsapptest.utils.FileUtils;
import com.shengdou.as.slopsapptest.utils.NetConstant;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UpdateAppService extends Service {

	private Context context;
	private Notification notification;
	private NotificationManager nManager;
	private PendingIntent pendingIntent;
	private String url;
	private boolean isUpdate;
	private int progress;
	private String TAG = "UpdataService";

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		context = getApplicationContext();
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub

		if (!isUpdate) {
			url = intent.getStringExtra("url");
			CreateInform();
		}
		return super.onStartCommand(intent, flags, startId);
	}

	// 创建通知
	public void CreateInform() {
		// 定义一个PendingIntent，当用户点击通知时，跳转到某个Activity(也可以发送广播等)
		// 创建一个通知
		notification = new Notification(R.mipmap.ic_logo, getString(R.string.str_down_coband),
				System.currentTimeMillis());
		notification.contentView = new RemoteViews(getPackageName(),R.layout.notification_download);
		notification.contentView.setProgressBar(R.id.pb, 50,0, false);
		Intent intent = new Intent(context, PhoneReceiver.class);
		pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
		notification.contentIntent = pendingIntent;
		// 用NotificationManager的notify方法通知用户生成标题栏消息通知
		nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		nManager.notify(100, notification);// id是应用中通知的唯一标识
		// 如果拥有相同id的通知已经被提交而且没有被移除，该方法会用更新的信息来替换之前的通知。
		new Thread(){
			@Override
			public void run() {
				try {
					DownLoadApp(url);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally {
					isUpdate = false;
				}
			}
		}.start();// 这个是下载的重点，是下载的过程

	}

	public void DownLoadApp(String urlString) throws Exception {
		if (BuildConfigs.DEBUG){
			Log.e(TAG, "开始更新");
		}
		isUpdate = true;
		URL url = new URL(urlString);
		HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
		long length = urlConnection.getContentLength();
		InputStream is = urlConnection.getInputStream();
		FileOutputStream fileOutputStream = null;
		if (is != null) {
			File file = FileUtils.getDownAppFile(context);
			if(file.exists()){
				file.delete();
			}
			fileOutputStream = new FileOutputStream(file);
			byte[] buf = new byte[1024];
			int ch;
			int count = 0;
			while ((ch = is.read(buf)) != -1) {
				fileOutputStream.write(buf, 0, ch);
				count += ch;
				if (length > 0) {
					int p = (int) (count * 50 / length);
					if(progress != p){
						progress = p;
						notification.contentView.setProgressBar(R.id.pb, 50, progress, false);
						notification.contentView.setTextViewText(R.id.down_tv, getString(R.string.str_downloaded) + (progress * 2) + "%");
						nManager.notify(100, notification);
					}
				}
				if (count == length) {
					progress = 50;
					notification.contentView.setProgressBar(R.id.pb, 50, 50, false);
					notification.contentView.setTextViewText(R.id.down_tv, getString(R.string.str_install_coband));
					nManager.notify(100, notification);
				}
			}
		}
		assert fileOutputStream != null;
		fileOutputStream.flush();
		fileOutputStream.close();
		sendBroadcast(new Intent(NetConstant.VERSION));
	}

}
